package com.roc.web.action.agent;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitRule;
import com.roc.pojo.TblInsInf;
import com.roc.service.IAgentService;
import com.roc.service.IMerchantServices;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.agent.IAgentInfoService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.InvoiceRateType;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SexStatus;

/**
 * 代理商管理action
 * @author zx-think
 *
 */

@Component
@Scope("prototype")
@Namespace("/agentQuery")
public class AgentSetAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(AgentQueryAction.class);
	
	private AgentSetSearchCondition searchCondition;
	

	
	private Operators merchant;
	
	private AuditingItem auditing;
	
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	private List<Operators> operatorsList=new ArrayList<Operators>();
	
	private String code;
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	IPageService pagenitionService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	
	@Autowired
	IAgentInfoService agentInfoService;
	@Autowired
	IMerchantServices merinfoService;
	@Autowired
	IAgentService  agentService;
	private Operators agent;
	
	private long agentId;
	
	private String from;
	
	
	@Action(value = "agentSetInit", results = { @Result(name = "success", location = "/pages/agent/agentSetList.jsp")
             })
    /**
     * 商户信息变更查询页初始化         
     */
	public String agentSetInit() throws Exception{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		// 如果当前登录账号非系统管理员/机构管理员/代理商，没有权限登陆
		if(!logingOperators.getRoleType().equals(Role.AGENT.getCode()) && !logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
				&& !logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode()) && !logingOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
				 && !logingOperators.getRoleType().equals(Role.O_MANAGER.getCode()) ){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		
		org();
		
		return SUCCESS;
	}
	
	@Action(value = "agentSetQuery", results = { @Result(name = "success", location = "/pages/agent/agentSetList.jsp")
           })
	//查询代理商
	public String queryAgentListInfoAction() throws Exception{
		
        Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
        
       
		if(searchCondition==null){
			searchCondition=(AgentSetSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new AgentSetSearchCondition();
			}
		}
		try {
			// 如果当前登录账号非系统管理员/机构管理员/代理商，没有权限登陆
			if(!logingMerchant.getRoleType().equals(Role.AGENT.getCode()) && !logingMerchant.getRoleType().equals(Role.SYSTEM.getCode())
					&& !logingMerchant.getRoleType().equals(Role.OPERATORS_COMM.getCode()) && !logingMerchant.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
					 && !logingMerchant.getRoleType().equals(Role.O_MANAGER.getCode()) ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			
			org();

			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");
			
			//当 当前账号/上级为代理商/机构管理员 时，只是查询直接下级代理
			if(superRole.equals(Role.AGENT.getCode()) 
					 || superRole.equals(Role.O_MANAGER.getCode()) ){
				searchCondition.setSuperId(new Long(opRealId));
			}
            // 受理市场标识
            searchCondition.setGroupCdFlag( map.get("groupCd") );
			//searchCondition.setStatus(OperatorsStatus.WAIT_AUDITING.getCode());  //查询代理商状态为  待审核   的
			//searchCondition.setOperators(logingMerchant);
			int rows=pagenitionService.countSQL(searchCondition);
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			agentTheListSpecially(searchRsList);
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

			getRequest().setAttribute("superRole", superRole);
			
			if("delete".equals(from)){
				getRequest().setAttribute("mes", "删除成功");
			}
			
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}
	/*
	@Action(value = "queryAgentViewInfo", results = { @Result(name = "success", location = "/pages/agent/agentView.jsp")
    })
	//查询代理商详细信息
	public String queryAgentViewAction(){
	Operators operators=new Operators();
	
	try {
		operators=agentInfoService.queryAgentInfo(merchant.getAccountNo());
		// 页面分润比例转化,分润比例 * 100
		List<ProfitPercent> perList = getNewPreList(operators.getProfitPerList());
		operators.setProfitPerList(perList);
		// 主账号隐藏中间数字
		String bankAcctNo = Utils.dealCardNo(operators.getBankAcctNo());
		operators.setBankAcctNo(bankAcctNo);
		
		Map auditingMap=new HashMap();
		auditingMap.put(AuditingResultCodeType.PASS.getCode(),AuditingResultCodeType.PASS.getName());
		auditingMap.put(AuditingResultCodeType.REFUSE.getCode(),AuditingResultCodeType.REFUSE.getName());
		auditingMap.put(AuditingResultCodeType.INCOMPLETE_INFO.getCode(),AuditingResultCodeType.INCOMPLETE_INFO.getName());
		
		getRequest().setAttribute("auditingMap",auditingMap);
		
		getRequest().setAttribute("agent", operators);
		Map<String,String> areaMap= ConfigProperties.getAreaCodeProperties();
		getRequest().setAttribute("areaName", areaMap.get(operators.getAreaCode()));
		
	} catch (Exception e) {
		logger.error(e.getMessage(),e);
		e.printStackTrace();
		addActionError(e.getMessage());
		return ERROR;
	}
	
	
	return SUCCESS;
	}*/
	
	//代理商修改初始
	@Action(value = "agentUpdateInit", results = {
			@Result(name = "success", location = "/pages/agent/agentSetUpdate.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  agentUpdateInit(){
		List orgList=new ArrayList();
		try {
			Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			orgList = orgService.queryOrgList();
			Operators operator = powerInfoService.loadOperatorsById(new Long(code));
			List<Object> audtingList=new ArrayList<Object>();
			audtingList=merinfoService.queryAuditingList(operator.getAccountNo());
			List<ProfitRule> ruleList = agentService.queryProfitRule(operator.getAccountNo());
			operator.setProList(ruleList);
			getRequest().setAttribute("audtingList", audtingList);
			getRequest().setAttribute("op",logingOperators);
			getRequest().setAttribute("agent",operator);
			getRequest().setAttribute("mccList", ConfigProperties.getMccTypeProperties());
			Map<String, String> map=dealAgentType(logingOperators.getFlag(), logingOperators.getAgentType(), ConfigProperties.getAgentTypeProperties());
			getRequest().setAttribute("agTypeList",map);
			getRequest().setAttribute("orgList", orgList);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			addActionError("加载代理商基本信息出错！！");
		}
		return SUCCESS;
	}
	
	
	//代理商信息变更
	@Action(value = "agentUpdate", results = {
			@Result(name = "success",type="redirect", location = "/agentQuery/agentSetQuery.ct"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  agentUpdate() throws Exception{
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Operators oldOP = powerInfoService.loadOperatorsById(agent.getId());
			agent.setOperators(logingOperators.getAccountNo());
			Date date=new Date();
			if(logingOperators.getId()==oldOP.getSuperiorId()){
				if(oldOP.getAccountNo()==null||"".equals(oldOP.getAccountNo().trim())){
					addActionError("代理商对应账号不存在,无法修改");
				}else{
					agentService.deleteProfitRuleByAgentId(oldOP.getAccountNo());
					agent.setValidStartDate(DateUtil.initStartDate(date));
					agent.setValidEndDate(DateUtil.initEndDate());
					agentService.editAgent(agent,oldOP,logingOperators);
				}
			}
			else{
				addActionError("数据修改权限不够");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		 getRequest().setAttribute("msg", "代理商信息补全资料成功！");
		 return "success";
	}
	
	//查询机构
	public void org() throws Exception{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		TblInsInf insInfBean = orgService.queryInsByCode(logingOperators.getOrgCode());
		orgList.add(insInfBean);
		
		getRequest().setAttribute("orgList", orgList);

		Map<String, String> map=powerInfoService.queryRealIdByOpId(logingOperators.getSuperiorId(), logingOperators.getRoleType(), logingOperators.getId(), logingOperators.getOrgCode());
        String superRole= map.get("superRole");
        
		String invoiceRateFlag = "0";
		// 如果当前登陆账号是系统管理员，则允许显示发票扣率
		if(logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
				 || ( superRole.equals(Role.SYSTEM.getCode()) 
						 && ( logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode()) || logingOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode()) ) ) ){
			invoiceRateFlag = "1";
		}
		getRequest().setAttribute("invoiceRateFlag", invoiceRateFlag);
	}
	
	protected void agentTheListSpecially(List<Object> list) {
    	List<Object> tempList=new ArrayList<Object>();
		for(Object object:list){
			
			Object[] obj = (Object[])object ; 
			Operators temp = new Operators();
			
			temp.setSuperiorId(Long.valueOf( Constance.Null2EmptyTrim( obj[0] ) )) ;// 
			temp.setStatus( Constance.Null2EmptyTrim( obj[1] ) ) ;// 
			temp.setAccountNo( Constance.Null2EmptyTrim( obj[2] ) )  ;// 
			temp.setId(Long.valueOf( Constance.Null2EmptyTrim( obj[3] ) )) ;// 
			temp.setRealName( Constance.Null2EmptyTrim( obj[4] ) ) ;// 
			temp.setSex( Constance.Null2EmptyTrim( obj[5] ) ) ;// 
			temp.setMobile( Constance.Null2EmptyTrim( obj[6] ) ) ;// 
			temp.setOrgCode( Constance.Null2EmptyTrim( obj[7] ) ) ;// 
			temp.setRoleType( Constance.Null2EmptyTrim( obj[8] ) ) ;// 
			temp.setCardNo( Constance.Null2EmptyTrim( obj[9] ) ) ;// 
			
			temp.setDtCreateFmt( Constance.Null2EmptyTrim( obj[10] ) ) ;// 
			temp.setDtLostmodFmt( Constance.Null2EmptyTrim( obj[11] ) ) ;// 
			temp.setTaxRegistrationCertificate( Constance.Null2EmptyTrim( obj[12] ) ) ;// 发票扣率
			temp.setOrganizationCode( Constance.Null2EmptyTrim( obj[13] ) ); // 序号编码

			temp.setSuperiorName( Constance.Null2EmptyTrim( obj[14] ) ); // 所属代理商名称
			temp.setOrgName( Constance.Null2EmptyTrim( obj[15] ) );// 机构名称
		
			//		手机用*代替
			temp.setMobile(Utils.dealMobile(temp.getMobile()));
			//		身份证用*代替
			temp.setCardNo(Utils.dealCardNo(temp.getCardNo()));
			
			temp.setSex(SexStatus.valueOfCode(temp.getSex()).getName());
			temp.setRoleName(Role.valueOfCode(temp.getRoleType()).getName());
			temp.setStatus(OperatorsStatus.valueOfCode(temp.getStatus()).getName());
			temp.setTaxRegistrationCertificate( ( !"".equals(temp.getTaxRegistrationCertificate()) ? 
						InvoiceRateType.valueOfCode(temp.getTaxRegistrationCertificate()).getName() : "") ); // 发票扣率
				
			tempList.add(temp);
		}
		searchRsList=tempList;
		
	}
	
	//删除代理商
	@Action(value = "deleteAgent", results = {
			@Result(name = "success",type="redirect", location = "/agentQuery/agentSetQuery.ct?from=delete"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String  deleteAgent(){
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(logingOperators==null){
			addActionError("已经超时,清重新登录");
			return ERROR;
		}
		try {
			Operators op = powerInfoService.loadOperatorsById(agentId);
			merchantServices.deleteMerInfo(agentId,logingOperators.getAccountNo(),op);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("删除代理商出错！！");
			return ERROR;
		}
		return SUCCESS;
	}
	
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (AgentSetSearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_AGENT_SET_INFO);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_AGENT_SET_INFO, searchCondition);
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}

	

	public AgentSetSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(AgentSetSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public AuditingItem getAuditing() {
		return auditing;
	}

	public void setAuditing(AuditingItem auditing) {
		this.auditing = auditing;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public List<Operators> getOperatorsList() {
		return operatorsList;
	}

	public void setOperatorsList(List<Operators> operatorsList) {
		this.operatorsList = operatorsList;
	}
	
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}


	public Operators getAgent() {
		return agent;
	}

	public void setAgent(Operators agent) {
		this.agent = agent;
	}

	public long getAgentId() {
		return agentId;
	}

	public void setAgentId(long agentId) {
		this.agentId = agentId;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	
}

